package com.chookss.home.interview;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.InvitationRegisterEntity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.InvitationRegisterBottomDialog;
import com.chookss.view.RecycleViewDivider;
import com.chookss.view.ShareQrCodeDialog;
import com.chookss.view.listener.HomeBottomDialogListener;
import com.chookss.view.listener.ShareDialogListener;
import com.chookss.wxapi.WeChatShareUtil;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

public class InvitationRegisterActivity extends BaseAct {
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    private Adapter adapter;
    private List<InvitationRegisterEntity> listData = new ArrayList<>();
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private String keyWords = "";
    private int index = -1;//默认不选择
    private Bitmap bitmapImg = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.common_srlview_center);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        NavigationTools.saveUseRecord(this, "2", "18");
        commonTitleTxt.setText("邀请注册");
        ivNone.setBackgroundResource(R.drawable.icon_default_no_common);
        tvNone.setText("暂无数据");
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) smrRf.getLayoutParams();
        params.setMargins(0, Utils.dip2px(this, 12), 0, 0);
        smrRf.setLayoutParams(params);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        adapter = new Adapter(R.layout.item_invitation_register, this, listData);
        recyclerView.setAdapter(adapter);
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        smrRf.autoRefresh();
        String picUrl = new ShareUtils().getString(this, StaticClass.COMPANYLOGO, "");
        try {
            Glide.with(this).asBitmap()
                    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).load(picUrl)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@androidx.annotation.NonNull Bitmap resource, @androidx.annotation.Nullable Transition<? super Bitmap> transition) {
                            try {
                                if (resource != null) {
                                    bitmapImg = resource;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", "20");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<InvitationRegisterEntity>>>() {
        }.getType(), null, Urls.selectRegistList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<InvitationRegisterEntity>>() {
            @Override
            public void onSuccess(List<InvitationRegisterEntity> data) {
                loadEnd();
                if (currentPage == 1) {
                    listData.clear();
                    adapter.notifyDataSetChanged();
                }
                if (smrRf == null || llNone == null) {
                    return;
                }
                int old = listData.size();
                if (data != null && data.size() > 0) {
                    listData.addAll(data);
                    adapter.notifyItemRangeChanged(old, data.size());
                    smrRf.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (listData.size() == 0) {
                        smrRf.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private String title = "";

    class Adapter extends BaseQuickAdapter<InvitationRegisterEntity, BaseViewHolder> {
        private Context context;

        public Adapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<InvitationRegisterEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolder helper, InvitationRegisterEntity item) {
            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvPermission = helper.getView(R.id.tvPermission);
            TextView tvSet = helper.getView(R.id.tvSet);
            TextView tvPost = helper.getView(R.id.tvPost);
            LinearLayout llShare = helper.getView(R.id.llShare);
            tvTitle.setText(item.getRegistName());
            tvPost.setText(item.getOrgName() + "/" + item.getPostName());
            tvPermission.setText("角色权限：" + item.getRoleNames());
//            是否设置后台账号(0否/1是)
            if ("1".equals(item.getPcFlag())) {
                tvSet.setText("后台账号：已设置");
            } else {
                tvSet.setText("后台账号：未设置");
            }
            llShare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    title="邀请你加入\""+item.getCompanyName() + "\"";
                    new InvitationRegisterBottomDialog(InvitationRegisterActivity.this, new HomeBottomDialogListener() {
                        @Override
                        public void onListItemClick(int position) {
                            if (position == 1) {
                                new ShareQrCodeDialog(InvitationRegisterActivity.this, title, item.getRegistUrl(),
                                        new ShareDialogListener() {
                                            @Override
                                            public void onClick() {
                                            }
                                        }).show();
                            } else if (position == 2) {
                                MyToast.show("已复制到剪切板");
                                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                clipboardManager.setPrimaryClip(ClipData.newPlainText("",  item.getRegistUrl()));
                            } else {
                                if (bitmapImg == null) {
                                    bitmapImg = BitmapFactory.decodeResource(getResources(), GlideUtils.loadPushId(InvitationRegisterActivity.this));
                                }
                                WeChatShareUtil.getInstance(InvitationRegisterActivity.this).shareUrl( item.getRegistUrl(), title, bitmapImg, "让学习和分享成为工作的一部分", SendMessageToWX.Req.WXSceneSession);
                            }
                        }
                    }).show();
                }
            });
        }
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick(R.id.common_title_back)
    public void onClick() {
        finish();
    }
}
